<template><!-- 文字展开收起组件 -->
  <div class="desc">
    <div :class="['text', {'active': isShow}]" :style="{height: textHeight && textHeight + 'px'}">
      <span class="btn" v-if="isShowBtn" @click="handleClick">{{state ? '收起' : '展开' }}</span>
      {{title}}
    </div>
  </div>
</template>

<script>
  export default {
    props: {
      title: String,
      lineClamp: {
        type: Number,
        default: 2,
      },
    },
    data() {
      return {
        isShow: false, // 展开、收起状态
        isShowBtn: false, // 展开、收起 是否展示
        state: false, // 展开还是收起
        textHeight: null, // text 高度 
        textInitialHeight: 0, // 元素初始高度
        textLineHeight: 0, // 元素行高
      }
    },
    created() {
    },
    mounted() {
      this.$nextTick(() => {
        const text = document.querySelector('.desc .text');
        const textStyle = window.getComputedStyle(text);
        const height = parseInt(textStyle.height);
        const lineHeight = parseInt(textStyle.lineHeight);
        this.textInitialHeight = height;
        this.textLineHeight = lineHeight;
        if (height >= lineHeight * 3) {
          this.isShow = true;
          this.isShowBtn = true;
          this.textHeight = lineHeight * 2;
        } else {
          this.textHeight = height;
        };
      })
    },
    watch: {
      state(val) {
        val ? this.textHeight = this.textInitialHeight : this.textHeight = this.textLineHeight * 2;
      }
    },
    methods: {
      handleClick() {
        this.isShow = !this.isShow;
        this.state = !this.state;
      }
    },

  }
</script>

<style scoped lang="less">
  .desc {
    padding: 0 24px;
    margin: 10px 0;
    display: flex;

    .text {
      font-size: 30px;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      color: #FFFFFF;
      line-height: 44px;
      transition: height .3s ease;
      overflow: hidden;

      .btn {
        margin-left: 6px;
        float: right;
        clear: both;
        width: 62px;
        height: 44px;
        line-height: 44px;
        font-size: 30px;
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        color: #848484;
        transform: translate(-6px, -4px);
      }

    }

    .text.active {
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;

    }

    .text::before {
      content: '';
      float: right;
      height: calc(100% - 40px);
    }

  }
</style>